#!/bin/bash

echo "=== MQTT网络连接测试 ==="

# 1. 检查网络连通性
echo "1. 检查基本网络连通性..."
ping -c 3 8.8.8.8 > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ 网络连接正常"
else
    echo "❌ 网络连接异常"
    exit 1
fi

# 2. 检查DNS解析
echo "2. 检查DNS解析..."
nslookup broker.hivemq.com > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ DNS解析正常"
    echo "   IP地址: $(nslookup broker.hivemq.com | grep 'Address:' | tail -1 | cut -d' ' -f2)"
else
    echo "❌ DNS解析失败"
fi

# 3. 检查端口连通性
echo "3. 检查MQTT端口连通性..."
timeout 5 bash -c "</dev/tcp/broker.hivemq.com/1883" > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ MQTT端口1883可访问"
else
    echo "❌ MQTT端口1883不可访问"
    echo "   尝试备用端口8000..."
    timeout 5 bash -c "</dev/tcp/broker.hivemq.com/8000" > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "✅ MQTT端口8000可访问"
    else
        echo "❌ MQTT端口8000也不可访问"
    fi
fi

# 4. 使用telnet测试(如果可用)
if command -v telnet >/dev/null 2>&1; then
    echo "4. 使用telnet测试MQTT连接..."
    timeout 3 telnet broker.hivemq.com 1883 </dev/null > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "✅ telnet测试成功"
    else
        echo "❌ telnet测试失败"
    fi
fi

# 5. 测试备用代理
echo "5. 测试备用MQTT代理..."
backup_brokers=("test.mosquitto.org" "broker.emqx.io" "mqtt.eclipseprojects.io")

for broker in "${backup_brokers[@]}"; do
    echo "   测试 $broker ..."
    timeout 3 bash -c "</dev/tcp/$broker/1883" > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "   ✅ $broker 可访问"
    else
        echo "   ❌ $broker 不可访问"
    fi
done

echo "=== 测试完成 ==="